package cn.iocoder.yudao.module.strategyPlanUser.service.strategyPlanUser;

import cn.iocoder.yudao.module.strategy.dal.dataobject.strategy.StrategyDO;
import cn.iocoder.yudao.module.strategy.service.strategy.StrategyService;
import cn.iocoder.yudao.module.strategyPlan.dal.dataobject.strategyPlan.StrategyPlanDO;
import cn.iocoder.yudao.module.strategyPlan.service.strategyPlan.StrategyPlanService;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.iocoder.yudao.module.strategyPlanUser.controller.admin.strategyPlanUser.vo.*;
import cn.iocoder.yudao.module.strategyPlanUser.dal.dataobject.strategyPlanUser.StrategyPlanUserDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.strategyPlanUser.convert.strategyPlanUser.StrategyPlanUserConvert;
import cn.iocoder.yudao.module.strategyPlanUser.dal.mysql.strategyPlanUser.StrategyPlanUserMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.strategyPlanUser.enums.ErrorCodeConstants.*;

/**
 * 企业战略-计划-人力落地表（短期、长期） Service 实现类
 *
 * @author huangjunwei
 */
@Service
@Validated
@Slf4j
public class StrategyPlanUserServiceImpl implements StrategyPlanUserService {

    @Resource
    private StrategyPlanUserMapper strategyPlanUserMapper;


    @Resource
    private StrategyService strategyService;

    @Resource
    private StrategyPlanService strategyPlanService;

    @Resource
    private DeptService deptService;

    @Resource
    private AdminUserService adminUserService;

    @Override
    public Long create(StrategyPlanUserCreateReqVO createReqVO) {
        // 插入
        StrategyPlanUserDO strategyPlanUserDO = StrategyPlanUserConvert.INSTANCE.convert(createReqVO);
        strategyPlanUserMapper.insert(strategyPlanUserDO);
        // 返回
        return strategyPlanUserDO.getId();
    }

    @Override
    public void update(StrategyPlanUserUpdateReqVO updateReqVO) {
        // 校验存在
        validateExists(updateReqVO.getId());
        // 更新
        StrategyPlanUserDO updateObj = StrategyPlanUserConvert.INSTANCE.convert(updateReqVO);
        strategyPlanUserMapper.updateById(updateObj);
    }

    @Override
    public void delete(Long id) {
        // 校验存在
        validateExists(id);
        // 删除
        strategyPlanUserMapper.deleteById(id);
    }

    private void validateExists(Long id) {
        if (strategyPlanUserMapper.selectById(id) == null) {
            throw exception(NOT_EXISTS);
        }
    }

    @Override
    public StrategyPlanUserDO get(Long id) {
        return strategyPlanUserMapper.selectById(id);
    }

    /**
     * 获得企业战略-计划-人力落地表（短期、长期）
     *
     * @param id 编号
     * @return 企业战略-计划-人力落地表（短期、长期）
     */
    @Override
    public StrategyPlanUserRespVO getStrategyPlanUserRespVO(Long id) {
        StrategyPlanUserDO strategyPlanUserDO = this.get(id);
        StrategyPlanUserRespVO strategyPlanUserRespVO = StrategyPlanUserConvert.INSTANCE.convert(strategyPlanUserDO);

        this.rebuildStrategyPlanUserRespVO(strategyPlanUserRespVO);
        return strategyPlanUserRespVO;
    }

    private void rebuildStrategyPlanUserRespVO(StrategyPlanUserRespVO strategyPlanUserRespVO) {
        /** 组织 */
        DeptDO dept = deptService.getDept(strategyPlanUserRespVO.getOrganizationId());
        if (dept != null) {
            strategyPlanUserRespVO.setOrganizationName(dept.getName());
        }

        /** 战略 */
        StrategyDO strategyDO = strategyService.get(strategyPlanUserRespVO.getStrategyId());
        if (strategyDO != null) {
            strategyPlanUserRespVO.setStrategyName(strategyDO.getStrategyName());
        }

        /** 战略计划 */
        StrategyPlanDO strategyPlanDO = strategyPlanService.get(Long.valueOf(strategyPlanUserRespVO.getStrategyPlanId()));
        if (strategyPlanDO != null) {
            strategyPlanUserRespVO.setStrategyPlanName(strategyPlanDO.getPlanName());
        }

        /** 用户 */
        //创建者+更新者+人才+领导
        Set<Long> userIdLongSet = new HashSet<>();
        userIdLongSet.add(Long.valueOf(strategyPlanUserRespVO.getCreator()));
        userIdLongSet.add(Long.valueOf(strategyPlanUserRespVO.getUpdater()));
        userIdLongSet.add(Long.valueOf(strategyPlanUserRespVO.getUserId()));
        userIdLongSet.add(strategyPlanUserRespVO.getLeaderId());

        //查用户
        List<AdminUserDO> adminUserDOList = adminUserService.getUserList(userIdLongSet);
        Map<Long, AdminUserDO> adminUserDOMap = new HashMap<>();
        adminUserDOList.forEach(item -> {
            adminUserDOMap.put(item.getId(), item);
        });
        //设置用户姓名
        AdminUserDO adminUserDOFromMap = null;
        //创建者
        adminUserDOFromMap = adminUserDOMap.get(Long.valueOf(strategyPlanUserRespVO.getCreator()));
        if (adminUserDOFromMap != null) {
            strategyPlanUserRespVO.setCreatorName(adminUserDOFromMap.getNickname());
        }
        //更新者
        adminUserDOFromMap = adminUserDOMap.get(Long.valueOf(strategyPlanUserRespVO.getUpdater()));
        if (adminUserDOFromMap != null) {
            strategyPlanUserRespVO.setUpdaterName(adminUserDOFromMap.getNickname());
        }
        //人才姓名
        adminUserDOFromMap = adminUserDOMap.get(Long.valueOf(strategyPlanUserRespVO.getUserId()));
        if (adminUserDOFromMap != null) {
            strategyPlanUserRespVO.setUserName(adminUserDOFromMap.getNickname());
        }
        //领导姓名
        adminUserDOFromMap = adminUserDOMap.get(strategyPlanUserRespVO.getLeaderId());
        if (adminUserDOFromMap != null) {
            strategyPlanUserRespVO.setLeaderName(adminUserDOFromMap.getNickname());
        }
    }

    @Override
    public List<StrategyPlanUserDO> getList(Collection<Long> ids) {
        return strategyPlanUserMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<StrategyPlanUserDO> getPage(StrategyPlanUserPageReqVO pageReqVO) {
        return strategyPlanUserMapper.selectPage(pageReqVO);
    }

    /**
     * 获得企业战略-计划-人力落地表（短期、长期）分页
     *
     * @param pageReqVO 分页查询
     * @return 企业战略-计划-人力落地表（短期、长期）分页
     */
    @Override
    public PageResult<StrategyPlanUserRespVO> getPageStrategyPlanUserRespVO(StrategyPlanUserPageReqVO pageReqVO) {
        PageResult<StrategyPlanUserDO> pageResult = this.getPage(pageReqVO);
        
        PageResult<StrategyPlanUserRespVO> strategyPlanUserRespVOPageResult = StrategyPlanUserConvert.INSTANCE.convertPage(pageResult);
        if (strategyPlanUserRespVOPageResult != null && !CollectionUtils.isEmpty(strategyPlanUserRespVOPageResult.getList())) {
            List<StrategyPlanUserRespVO> strategyPlanUserRespVOList = strategyPlanUserRespVOPageResult.getList();
            this.rebuildStrategyPlanUserRespVOList(strategyPlanUserRespVOList);
        }
        return strategyPlanUserRespVOPageResult;
    }

    private void rebuildStrategyPlanUserRespVOList(List<StrategyPlanUserRespVO> strategyPlanUserRespVOList) {
        if (CollectionUtils.isEmpty(strategyPlanUserRespVOList)) {
            return;
        }

        /** 组织 */
        Set<Long> deptIdSet = strategyPlanUserRespVOList.stream()
                .filter(Objects::nonNull)
                .map(StrategyPlanUserBaseVO::getOrganizationId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        //查组织
        List<DeptDO> deptDOList = deptService.getDeptList(deptIdSet);
        Map<Long, DeptDO> deptDOMap = new HashMap<>();
        deptDOList.forEach(item -> {
            deptDOMap.put(item.getId(), item);
        });
        //设置组织
        for (StrategyPlanUserRespVO strategyPlanUserRespVO : strategyPlanUserRespVOList) {
            if (deptDOMap.get(strategyPlanUserRespVO.getOrganizationId()) != null) {
                strategyPlanUserRespVO.setOrganizationName(deptDOMap.get(strategyPlanUserRespVO.getOrganizationId()).getName());
            }
        }

        /** 战略 */
        Set<Long> strategyIdLongSet = strategyPlanUserRespVOList.stream()
                .filter(Objects::nonNull)
                .map(StrategyPlanUserBaseVO::getStrategyId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        //查战略
        List<StrategyDO> strategyDOList = strategyService.getList(strategyIdLongSet);
        Map<Long, StrategyDO> strategyDOMap = new HashMap<>();
        strategyDOList.forEach(item -> {
            strategyDOMap.put(item.getId(), item);
        });
        //设置战略
        for (StrategyPlanUserRespVO strategyPlanUserRespVO : strategyPlanUserRespVOList) {
            if (strategyDOMap.get(strategyPlanUserRespVO.getStrategyId()) != null) {
                strategyPlanUserRespVO.setStrategyName(strategyDOMap.get(strategyPlanUserRespVO.getStrategyId()).getStrategyName());
            }
        }

        /** 计划 */
        Set<Long> strategyPlanIdLongSet = strategyPlanUserRespVOList.stream()
                .filter(Objects::nonNull)
                .map(item -> {
                    if (StringUtils.isNotBlank(item.getStrategyPlanId()) ) {
                        return Long.valueOf(item.getStrategyPlanId());
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        //查计划
        List<StrategyPlanDO> strategyPlanDOList = strategyPlanService.getList(strategyPlanIdLongSet);
        Map<Long, StrategyPlanDO> strategyPlanDOMap = new HashMap<>();
        strategyPlanDOList.forEach(item -> {
            strategyPlanDOMap.put(item.getId(), item);
        });
        //设置计划
        for (StrategyPlanUserRespVO strategyPlanUserRespVO : strategyPlanUserRespVOList) {
            if (StringUtils.isEmpty(strategyPlanUserRespVO.getStrategyPlanId())) {
                continue;
            }
            if (strategyPlanDOMap.get(Long.valueOf(strategyPlanUserRespVO.getStrategyPlanId())) != null) {
                strategyPlanUserRespVO.setStrategyPlanName(strategyPlanDOMap.get(Long.valueOf(strategyPlanUserRespVO.getStrategyPlanId())).getPlanName());
            }
        }

        /** 用户 */
        //创建者+更新者+决策者
        Set<String> userIdStringSet = strategyPlanUserRespVOList.stream()
                .filter(Objects::nonNull)
                .flatMap(item -> {
                    //todo 待优化，部分数据可能出现空指针
                    return Stream.of(item.getCreator(), item.getUpdater(), item.getUserId(), String.valueOf(item.getLeaderId()));
                })
                .filter(id -> StringUtils.isNotBlank(id))
                .collect(Collectors.toSet());
        //将Set<String>转换为Set<Long>
        Set<Long> userIdLongSet = userIdStringSet.stream()
                .map(userIdString -> {
                    try {
                        return Long.parseLong(userIdString);
                    } catch (Exception e) {
                        log.error("用户相关数据异常，strategyPlanUserRespVOList：" + JSON.toJSONString(strategyPlanUserRespVOList), e);
                        return null;
                    }
                })
                .filter(Objects::nonNull) // 过滤掉空的
                .collect(Collectors.toSet());
        //查用户
        List<AdminUserDO> adminUserDOList = adminUserService.getUserList(userIdLongSet);
        Map<Long, AdminUserDO> adminUserDOMap = new HashMap<>();
        adminUserDOList.forEach(item -> {
            adminUserDOMap.put(item.getId(), item);
        });
        //设置用户姓名
        for (StrategyPlanUserRespVO strategyPlanUserRespVO : strategyPlanUserRespVOList) {
            AdminUserDO adminUserDOFromMap = null;
            //创建者
            if (StringUtils.isNotBlank(strategyPlanUserRespVO.getCreator())) {
                adminUserDOFromMap = adminUserDOMap.get(Long.valueOf(strategyPlanUserRespVO.getCreator()));
                if (adminUserDOFromMap != null) {
                    strategyPlanUserRespVO.setCreatorName(adminUserDOFromMap.getNickname());
                }
            }
            //更新者
            if (StringUtils.isNotBlank(strategyPlanUserRespVO.getUpdater())) {
                adminUserDOFromMap = adminUserDOMap.get(Long.valueOf(strategyPlanUserRespVO.getUpdater()));
                if (adminUserDOFromMap != null) {
                    strategyPlanUserRespVO.setUpdaterName(adminUserDOFromMap.getNickname());
                }
            }
            //人才姓名
            if (StringUtils.isNotBlank(strategyPlanUserRespVO.getUserId())) {
                adminUserDOFromMap = adminUserDOMap.get(Long.valueOf(strategyPlanUserRespVO.getUserId()));
                if (adminUserDOFromMap != null) {
                    strategyPlanUserRespVO.setUserName(adminUserDOFromMap.getNickname());
                }
            }
            //领导姓名
            if (strategyPlanUserRespVO.getLeaderId() != null) {
                adminUserDOFromMap = adminUserDOMap.get(strategyPlanUserRespVO.getLeaderId());
                if (adminUserDOFromMap != null) {
                    strategyPlanUserRespVO.setLeaderName(adminUserDOFromMap.getNickname());
                }
            }
        }
    }

    @Override
    public List<StrategyPlanUserDO> getList(StrategyPlanUserExportReqVO exportReqVO) {
        return strategyPlanUserMapper.selectList(exportReqVO);
    }

}
